/*
 * minet_utils.c
 *
 *  Created on: 2019年4月27日
 *      Author: 0yfj0
 */

#include <string.h>
#include <sys.h>
#include "minet.h"

/*----------------------------------------------------------------------------*/
uint8_t minet_sign(uint8_t nid, uint8_t *buf, int len)
{
	uint8_t sum;
	int i;

	if (!buf || len < 0)
		return 0;

	for (i = 0, sum = nid; i < len; ++i)
		sum += buf[i];

	return sum;
}

uint8_t minet_crc8(uint8_t *buf, int len)
{
	uint8_t sum;
	int i;

	if (!buf || len < 0)
		return 0;

	for (i = 0, sum = 0; i < len; ++i)
		sum += buf[i];

	return (~sum);
}

minet_msg_t *minet_msg_malloc(int sz)
{
	minet_msg_t *msg;

	if (sz < 0)
		return NULL;

	msg = (minet_msg_t*) sys_malloc(sizeof(minet_msg_t) + sz);
	if (msg != NULL)
	{
		memset(msg, 0, sz);
		msg->buf = (uint8_t*) msg + sizeof(minet_msg_t);
		msg->len = sz;
	}
	return msg;
}

void minet_msg_free(minet_msg_t *ptr)
{
	if (ptr != NULL)
	{
		sys_free(ptr);
	}
}

#if (MINET_GATEWAY)
minet_node_t *minet_node_alloc(uint16_t dest, int hops, uint8_t *pingdat)
{
	minet_node_t *node = (minet_node_t*) sys_malloc(sizeof(minet_node_t));
	if (node != NULL)
	{
		memset(node, 0, sizeof(minet_node_t));
		node->dest = dest;
		node->hops = hops;
		if (pingdat != NULL)
			memcpy(node->pingdat, pingdat, MINET_PINGDATA_LEN);
		node->stamp = minet_hal_tick1s();
	}
	return node;
}
#endif
